package com.jeeplus.modules.sys.web.WeChat;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.io.IOUtil;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.web.WeChat.handler.AtsEventMessageHandler;
import com.jeeplus.modules.sys.web.WeChat.handler.AtsNormalMessageHandler;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.Configuration;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.http.HttpClient;
import org.weixin4j.model.message.InputMessage;
import org.weixin4j.model.message.MsgType;
import org.weixin4j.model.message.OutputMessage;
import org.weixin4j.model.message.event.ScanCodePushEventMessage;
import org.weixin4j.model.message.normal.TextInputMessage;
import org.weixin4j.model.message.output.TextOutputMessage;
import org.weixin4j.spi.HandlerFactory;
import org.weixin4j.spi.IMessageHandler;
import org.weixin4j.util.TokenUtil;
import org.weixin4j.util.XStreamFactory;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.logging.Logger;

/**
 * @author Administrator
 * @title: WeixinJieruController
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/10/17:36
 */
@Controller
@RequestMapping(value = "/api/WebChat/")
@CrossOrigin
public class WeixinJieruController extends BaseController{
    private final AtsNormalMessageHandler normalMessageHandler=new AtsNormalMessageHandler();
    private final AtsEventMessageHandler eventMessageHandler=new AtsEventMessageHandler();
    //开发者接入验证
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //消息来源可靠性验证
       // response.getWriter().write("test");
        System.out.println("test");
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        //Token为weixin4j.properties中配置的Token
        String token = TokenUtil.get();
        System.out.println(token);
        //1.验证消息真实性
        //http://mp.weixin.qq.com/wiki/index.php?title=验证消息真实性
        //成为开发者验证
        String echostr = request.getParameter("echostr");
        System.out.println(echostr);
//        //确认此次GET请求来自微信服务器，原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
       try {
           if (TokenUtil.checkSignature(token, signature, timestamp, nonce)) {
               response.getWriter().write(echostr);
           }
       }
       catch (Exception e){
           e.printStackTrace();
       }
    }
    //接收微信消息
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public void post(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        //Token为weixin4j.properties中配置的Token
        String token = TokenUtil.get();
        //确认此次GET请求来自微信服务器，原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
        if (!TokenUtil.checkSignature(token, signature, timestamp, nonce)) {
            //消息不可靠，直接返回
            response.getWriter().write("");
            return;
        }
        //用户每次向公众号发送消息、或者产生自定义菜单点击事件时，响应URL将得到推送
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/xml");
            //获取POST流
            ServletInputStream in = request.getInputStream();
            //非注解方式，依然采用消息处理工厂模式调用
            IMessageHandler messageHandler = HandlerFactory.getMessageHandler();
            //处理输入消息，返回结果
//            String xml = messageHandler.invoke(in);
//            System.out.println(xml);
            //返回结果
            String xml=messageHander(in).toXML();
            response.getWriter().write(xml);
        } catch (IOException | WeixinException ex) {
            response.getWriter().write("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /***
     * 处理输入消息并返回结果
     *
     * @Author LH
     * @Description //TODO
     * @Date 18:29 2019/10/17
     * @param inputStream
     * @return org.weixin4j.model.message.OutputMessage
     **/
    public OutputMessage messageHander(ServletInputStream inputStream) throws Exception {
        OutputMessage outputMsg = null;
        String xmlMsg = XStreamFactory.inputStream2String(inputStream);
        JAXBContext context = JAXBContext.newInstance(InputMessage.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        InputMessage inputMsg = (InputMessage) unmarshaller.unmarshal(new StringReader(xmlMsg));
        String msgType = inputMsg.getMsgType();
        try {

            if (Configuration.isDebug()) {
                System.out.println(xmlMsg);
            }
            if (msgType.equals(MsgType.Text.toString()))
            {
                inputMsg.setContent(inputMsg.getContent());
                outputMsg = normalMessageHandler.textTypeMsg(inputMsg.toTextInputMessage());
            }
            if(msgType.equals(MsgType.Event.toString())){
                if(inputMsg.getEventKey().equals("扫码带提示")){
                    outputMsg = eventMessageHandler.scanCodePush(inputMsg.toScanCodePushEventMessage());
                }
                else {
                    inputMsg.setContent(MessageFormat.format("【{0}】功能暂未开放",inputMsg.getMsgType()));
                    outputMsg = normalMessageHandler.textTypeMsg(inputMsg.toTextInputMessage());
                }
            }
            else {
                inputMsg.setContent(MessageFormat.format("【{0}】功能暂未开放",inputMsg.getMsgType()));
                outputMsg = normalMessageHandler.textTypeMsg(inputMsg.toTextInputMessage());
            }

            if (outputMsg != null) {
                //设置收件人消息
                setOutputMsgInfo(outputMsg, inputMsg);
            }
            System.out.println(outputMsg.toXML());
        }
        catch (Exception e){
            inputMsg.setContent(MessageFormat.format("【{0}】暂未开放",inputMsg.getEventKey()));
            if (outputMsg != null) {
                //设置收件人消息
                setOutputMsgInfo(outputMsg, inputMsg);
            }
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return outputMsg;
    }
    /***
     * 设置发送信息
     *
     * @Author LH
     * @Description //TODO
     * @Date 18:30 2019/10/17
     * @param oms
     * @param msg
     * @return void
     **/
    private  void setOutputMsgInfo(OutputMessage oms, InputMessage msg) throws Exception {

        oms.setCreateTime(System.currentTimeMillis());
        oms.setToUserName(msg.getFromUserName());
        oms.setFromUserName(msg.getToUserName());
    }
    public static void main(String[] args) throws IOException {
        new HttpClient().download("http://mmbiz.qpic.cn/mmbiz_jpg/pOP6pR8JKuUKfQEicUJibejWO35icJn5u0Gw8mNuKvMWQ1oC1zfibaJkEJWRJh8ibvVeVw7Hx82HicBtFpX1KGmzmPYg/0").saveToImageFile("d:\\","123123.jpg");
    }
}
